﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace gt.dotnetcore.webapi.extension
{
    public static class HttpRequestExtensions
    {
        private const string HTTPCONTEXT = "MS_HttpContext";
        private const string REMOTE_ENDPOINT_MESSAGE = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
        private const string REMOTE_PORT = "REMOTE_PORT";
        private const string OWINCONTEXT = "MS_OwinContext";
        private const string X_REAL_IP = "x-real-ip";

        public static string GetRequestId(this HttpRequest request)
        {
            return request.HttpContext.TraceIdentifier;
        }

        public static string GetAppkey(this HttpRequest request)
        {
            var appkey = string.Empty;
            if (request.HttpContext.User != null)
                appkey = request.HttpContext.User.Identity.Name;
            return appkey;
        }

        public static string GetClientRealIp(this HttpRequest request)
        {
            string realIp = "0.0.0.0";
            if (request.Headers.ContainsKey(HTTPCONTEXT))
            {
                dynamic ctx = request.Headers[HTTPCONTEXT];
                if (ctx != null)
                    return ctx.Request.UserHostAddress;
            }
            if (request.Headers.ContainsKey(REMOTE_ENDPOINT_MESSAGE))
            {
                dynamic remoteEndpoint = request.Headers[REMOTE_ENDPOINT_MESSAGE];
                if (remoteEndpoint != null)
                    return remoteEndpoint.Address;
            }
            if (request.Headers.ContainsKey(OWINCONTEXT))
            {
                dynamic owinContext = request.Headers[OWINCONTEXT];//Microsoft.Owin.OwinContext
                if (owinContext != null)
                {
                    realIp = owinContext.Request.Headers[X_REAL_IP];
                    if (string.IsNullOrEmpty(realIp))
                        return owinContext.Request.RemoteIpAddress;
                }
            }
            return realIp;
        }
    }
}
